package br.com.buildup.cripto;

import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CryptographyTripeDES implements Cryptography {

    private Cipher cipher;
    private byte[] encryptKey;
    private KeySpec keySpec;
    private SecretKeyFactory secretKeyFactory;
    private SecretKey secretKey;

    static CryptographyTripeDES newInstance() throws Exception {
        return new CryptographyTripeDES();
    }

    private CryptographyTripeDES() throws Exception {
        super();

        String key = "http://www.buildupit.com.br";
        encryptKey = key.getBytes("ISO-8859-1");
        cipher = Cipher.getInstance("DESede");
        keySpec = new DESedeKeySpec(encryptKey);
        secretKeyFactory = SecretKeyFactory.getInstance("DESede");
        secretKey = secretKeyFactory.generateSecret(keySpec);
    }

    public String encrypt(String value) throws Exception {
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] cipherText = cipher.doFinal(value.getBytes("ISO-8859-1"));
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(cipherText);
    }

    public String decrypt(String value) throws Exception {
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        BASE64Decoder dec = new BASE64Decoder();
        byte[] decipherText = cipher.doFinal(dec.decodeBuffer(value));
        return new String(decipherText);
    }
}
